package com.matt.service.impl;

import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.domain.ComplaintRecord;
import com.matt.domain.mp.ParentUser;
import com.matt.domain.rel.RelClassesChildren;
import com.matt.domain.rel.RelClassesTeacher;
import com.matt.foundation.constant.RoleCodeConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.repository.AppUserRepository;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.ComplaintRecordRepository;
import com.matt.repository.rel.RelClassesChildrenRepository;
import com.matt.repository.rel.RelClassesTeacherRepository;
import com.matt.service.ComplaintRecordService;
import com.matt.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ComplaintRecordServiceImpl implements ComplaintRecordService {

    @Autowired
    ComplaintRecordRepository complaintRecordRepository ;

    @Autowired
    AppUserRepository appUserRepository;

    @Autowired
    ChildrenRepository childrenRepository;

    @Autowired
    RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    ClassesRepository classesRepository;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RelClassesTeacherRepository relClassesTeacherRepository;

//    @Autowired
//    private RedPointService redPointService;

    @Override
    public ComplaintRecord addComplaintRecord(String usersId, String childrenId, String complaintObject, String title, String content, MultipartFile[] files) {

        ParentUser users = appUserRepository.getOne(usersId);
        if(null == users)
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "家长不存在");
        String usersName = users.getName();

        Children children = childrenRepository.getOne(childrenId);
        if(null == children)
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        String childrenName = children.getName();
        String areaId = children.getAreaId();
        String resourceUrl = "";
        if(files.length >0){
            resourceUrl =  uploadService.uploadComplaintRecordImg(usersId, files);
        }

            ComplaintRecord record = new ComplaintRecord();
            record.setAreaId(areaId);
            record.setChildrenId(childrenId);
            record.setChildrenName(childrenName);
            record.setUsersId(usersId);
            record.setUsersName(usersName);
            record.setComplaintObjet(complaintObject);
            record.setComplaintTitle(title);
            record.setComplaintContent(content);
            record.setResourceUrl(resourceUrl);
            record.setIsReply(false);
            complaintRecordRepository.save(record);


        //触发红点，罗英如果参考此方法，记得复制红点逻辑
        //redPointService.addRedNumByComplaint(areaId,childrenId,complaintObject,1);

        return record;

    }

    @Override
    public ComplaintRecord addComplaintRecord(String parentPhone, String childrenId, String complaintObject, String title, String content, String files) {

        ParentUser users = appUserRepository.findByPhone(parentPhone);
        if(null == users)
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "家长不存在");
        String usersName = users.getName();

        Children children = childrenRepository.getOne(childrenId);
        if(null == children)
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        String childrenName = children.getName();
        String areaId = children.getAreaId();
        String resourceUrl = StringUtils.isEmpty(files)?"":files;

        ComplaintRecord record = new ComplaintRecord();
        record.setAreaId(areaId);
        record.setChildrenId(childrenId);
        record.setChildrenName(childrenName);
        record.setUsersId(users.getId());
        record.setUsersName(usersName);
        record.setComplaintObjet(complaintObject);
        record.setComplaintTitle(title);
        record.setComplaintContent(content);
        record.setResourceUrl(resourceUrl);
        record.setIsReply(false);
        complaintRecordRepository.save(record);

        //触发红点
        //redPointService.addRedNumByComplaint(areaId,childrenId,complaintObject,1);

        return record;

    }

    @Override
    public Page<ComplaintRecord> getComplaintRecord(String usersId, Integer pageNum, Integer pageSize) {
        Specification<ComplaintRecord> specification = new Specification<ComplaintRecord>() {
            @Override
            public Predicate toPredicate(Root<ComplaintRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.isNotBlank(usersId))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("usersId"), usersId)));
                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"),false )));
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("created")));
                return query.getRestriction();
            }
        };
        Page<ComplaintRecord> page = complaintRecordRepository.findAll(specification, PageRequest.of(pageNum, pageSize));
        List<ComplaintRecord> list = Lists.newArrayList();
        page.getContent().stream().forEach(o -> {
            list.add(o);
        });

        return new PageImpl(list, PageRequest.of(pageNum, pageSize), page.getTotalElements());
    }

    @Override
    public ComplaintRecord deleteComplaintRecord(String staffId,String staffName,String complaintRecordId) {
        ComplaintRecord record = complaintRecordRepository.getOne(complaintRecordId);
        if(null == record)
            throw new BusinessException(ErrorCode.ID_IS_ERROR, "投诉ID不存在");
        record.setDeleted(true);
        record.setStaffName(staffName);
        record.setStaffId(staffId);
        complaintRecordRepository.save(record);
        return record;
    }

    @Override
    public Page<ComplaintRecord> getComplaintRecordByRoleCode(String areaId,String staffId,String roleCode,String queryRoleCode,Boolean isReply, Integer pageNum, Integer pageSize) {

        List<String> classIdList = new ArrayList<>();
        List<String> childrenIdList = new ArrayList<>();

        if(roleCode.equals(RoleCodeConstant.ROLE_CODE_TEACHER)) {
            List<RelClassesTeacher> relClassesTeacherList = relClassesTeacherRepository.findByStaffId(staffId);//查询老师关联的班级
            for (RelClassesTeacher relClassesTeacher : relClassesTeacherList) {
                classIdList.add(relClassesTeacher.getClassesId());
            }

            List<RelClassesChildren> relClassesChildrenList =   relClassesChildrenRepository.findAllByClassesIdIn(classIdList);

            for (RelClassesChildren relClassesChildren : relClassesChildrenList) {
                childrenIdList.add(relClassesChildren.getChildrenId());
            }
            String[] strings = new String[childrenIdList.size()];
           childrenIdList.toArray(strings);

        }

        Specification<ComplaintRecord> specification = new Specification<ComplaintRecord>() {
            @Override
            public Predicate toPredicate(Root<ComplaintRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(areaId))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), areaId)));
                if (isReply != null)
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("isReply"), isReply)));
                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"),false )));

                if(roleCode.equals(RoleCodeConstant.ROLE_CODE_LEADER)){
                //园长查询所有记录
                    if (StringUtils.isNotBlank(queryRoleCode))
                        predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("complaintObjet"), queryRoleCode)));
                }else
                if(roleCode.equals(RoleCodeConstant.ROLE_CODE_BUSINESS)|| roleCode.equals(RoleCodeConstant.ROLE_CODE_DOCTOR)){
                //如果是销售或儿保 只能看自己对应角色的
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("complaintObjet"), roleCode)));
                }else
                if(roleCode.equals(RoleCodeConstant.ROLE_CODE_TEACHER) && childrenIdList.size() > 0) {
                        Expression<String> exp = root.<String>get("childrenId");
                        predicates.add(exp.in(childrenIdList));

                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.asc(root.get("isReply")));
                return query.getRestriction();
            }
        };


        Page<ComplaintRecord> page = complaintRecordRepository.findAll(specification, PageRequest.of(pageNum, pageSize));

        return page;
    }

    @Override
    public Page<ComplaintRecord> getComplaintRecord(List<String> areaIds, String roleCode,
                                                       String queryRoleCode, Boolean isReply,
                                                       Integer pageNum, Integer pageSize){

        Specification<ComplaintRecord> specification = new Specification<ComplaintRecord>() {
            @Override
            public Predicate toPredicate(Root<ComplaintRecord> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (isReply != null)
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("isReply"), isReply)));

                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"),false )));


                //查询所有记录
                if (StringUtils.isNotBlank(queryRoleCode))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("complaintObjet"), queryRoleCode)));

                Expression<String> exp = root.<String>get("areaId");
                predicates.add(exp.in(areaIds));

                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.asc(root.get("isReply")));
                return query.getRestriction();
            }
        };

        Sort sort = Sort.by("created").descending();

        PageRequest pager = PageRequest.of(pageNum, pageSize, sort);

        Page<ComplaintRecord> page = complaintRecordRepository.findAll(specification, pager);

        return page;
    }


    @Override
    public ComplaintRecord replyComplaintRecord(String staffId, String staffName, String complaintRecordId,String replyContent) {
        ComplaintRecord record = complaintRecordRepository.getOne(complaintRecordId);
        if(null == record)
            throw new BusinessException(ErrorCode.ID_IS_ERROR, "投诉ID不存在");

        record.setIsReply(true);
        record.setReplyDate(new Date());
        record.setReplyContent(replyContent);
        record.setStaffName(staffName);
        record.setStaffId(staffId);
        complaintRecordRepository.save(record);
        return record;
    }
}
